//
//  PictureWallViewController.m
//  WindRunner
//
//  Created by leeqb on 3/2/15.
//  Copyright (c) 2015 poweropt. All rights reserved.
//

#import "PictureWallViewController.h"
#import "AFURLConnectionOperation.h"
#import "AFURLSessionManager.h"
#import "AFHTTPRequestOperationManager.h"
#import "PictureWallDetailController.h"

#define KEY_FIND_TERMS_AGREE    @"FindTermsAgree"

@interface PictureWallViewController ()
{
    CGFloat _cellWidthAndHeight;
    NSMutableArray *_totalData;
    NSDictionary *_currRowData;
    NSArray *_currPageData;
    UIRefreshControl *_refreshControl;
    CGFloat _footerHeight;
    NSInteger _currPageCount;
    
    UIViewController *_termsVC;
}
@end

@implementation PictureWallViewController

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self) {
        self.navigationItem.hidesBackButton = YES;
        _totalData = [[NSMutableArray alloc] init];
        
        _cellWidthAndHeight = SCREEN_WIDTH / 2;
        _footerHeight = 0;
        self.currPageNum = 1;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _refreshControl = [[UIRefreshControl alloc] init];
    [_refreshControl addTarget:self action:@selector(loadFirstPage) forControlEvents:UIControlEventValueChanged];
    [_picCollectionView addSubview:_refreshControl];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationItem.title = LocalStringFind(@"NAV_TITLE");
    
    self.currPageNum = 1;
    [self loadPageData:self.currPageNum];
    if(![[NSUserDefaults standardUserDefaults] boolForKey:KEY_FIND_TERMS_AGREE] && !_termsVC) {
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed:@"FindTermsController" owner:self options:nil];
        _termsVC = arr[0];
        [self presentViewController:_termsVC animated:YES completion:^{
        }];
    }
}

- (IBAction)agreeButtonClicked:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:KEY_FIND_TERMS_AGREE];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }];
}

- (IBAction)disagreeButtonClicked:(UIButton *)sender {
    [FMToast showMessage:LocalStringFind(@"FIND_TERMS_DISAGREE")];
}

// 加载数据
- (void)loadPageData:(NSInteger)pageNum
{
    if(!self.dataLoading) {
        self.dataLoading = YES;
        NSDictionary *requestData = @{@"pageindex":[NSNumber numberWithInteger:pageNum],
                                      @"pagesize":LIST_PAGE_SIZE};
        FMRequestObject *requestObj = [[FMRequestObject alloc] initWithRUL:BASE_API_URL_WINDRUNNER
                                                                 interface:@"picturewall"
                                                                    params:requestData];
        [FMNetwork request:requestObj showMask:NO success:^(NSDictionary *data) {
            if(self.currPageNum == 1) {
                [_totalData removeAllObjects];
                [_picCollectionView reloadData];
            }
            
            [self loadPageDataEnd];
            _currPageData = data[@"record"][@"data"];
            if(![_currPageData isEqual:[NSNull null]] && _currPageData.count>0) {
                _currPageCount = _currPageData.count;
                [_totalData addObjectsFromArray:_currPageData];
                [_picCollectionView reloadData];
            }
        } falied:^(NSError *error) {
            [self loadPageDataEnd];
        }];
    }
}

- (void)loadPageDataEnd
{
    self.dataLoading = NO;
    [_refreshControl endRefreshing];
}

#pragma mark UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _totalData.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PictureWallCell" forIndexPath:indexPath];
    
    UIImageView *cellImageView = (UIImageView *)[cell viewWithTag:1];
    cellImageView.image = [UIImage getDefaultImageInSize:cellImageView.frame.size];
    NSDictionary *rowData = _totalData[indexPath.row];
    LEDownloadManager *downloadManager = [[LEDownloadManager alloc] initWithTarget:cellImageView];
    [downloadManager downLoadImageWithURL:rowData[@"url"] imagetype:@"PictureWallImages"];
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *tempView = nil;
    if([kind isEqual:UICollectionElementKindSectionFooter]) {
        tempView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"collectionFooterView" forIndexPath:indexPath];
    }
    
    return tempView;
}

#pragma mark UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(_cellWidthAndHeight, _cellWidthAndHeight);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.5;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(SCREEN_WIDTH, 0);
}

#pragma mark UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    /*UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:nil
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"举报", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];*/
    _currRowData = _totalData[indexPath.row];
    [self performSegueWithIdentifier:@"segPictureWallDetail" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"segPictureWallDetail"]) {
        PictureWallDetailController *vc = (PictureWallDetailController *)segue.destinationViewController;
        vc.data = _currRowData;
    }
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row==(_totalData.count-1) && _currPageCount==[LIST_PAGE_SIZE integerValue]) {
        self.currPageNum++;
        [self loadPageData:self.currPageNum];
    }
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0) {
        UIAlertView *alertForCancel = [[UIAlertView alloc] initWithTitle: LocalStringFind(@"REPORT_ALERT_TITLE")
                                                                 message: nil
                                                                delegate: self
                                                       cancelButtonTitle: LocalStringCommon(@"ALERT_CANCEL")
                                                       otherButtonTitles: LocalStringCommon(@"ALERT_OK"), nil];
        alertForCancel.alertViewStyle = UIAlertViewStylePlainTextInput;
        [alertForCancel show];
    }
}

#pragma mark UIAlertViewDelegate
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
    UITextField *txt = [alertView textFieldAtIndex:0];
    NSString *inputContent = [NSString formatString:txt.text];
    if([inputContent isEqualToString:@""]) {
        return NO;
    } else {
        return YES;
    }
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [FMToast showLoading:LocalStringCommon(@"OPER_DOING")];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [FMToast hide];
                [FMToast showMessage:LocalStringFind(@"REPORT_SUCCESS")];
            });
        });
    }
}

- (IBAction)takePhoto:(id)sender {
    PickImageView *pickView = [[PickImageView alloc] init];
    pickView.delegate = self;
    [pickView show];
}

// 下拉刷新，加载第一页数据
- (void)loadFirstPage
{
    self.currPageNum = 1;
    _totalData = [[NSMutableArray alloc] init];
    [self loadPageData:self.currPageNum];
}

- (void)imageTypeSelected:(UIImagePickerController *)vc
{
    vc.delegate = self;
    [self presentViewController:vc animated:YES completion:^{
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:^{
        [FMToast showLoading:LocalStringCommon(@"OPER_DOING")];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSString *urlString = [NSString stringWithFormat:@"%@addpicture", BASE_API_URL_WINDRUNNER];
            NSDictionary *requestData = @{@"userid":[AuthHelper getCurrentUser][@"id"]};
            
            AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
            httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];;
            
            NSData *imageData = UIImagePNGRepresentation(editedImage);
            NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:requestData constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                if(imageData) {
                    [formData appendPartWithFileData:imageData name:@"url" fileName:@"PictureWallImage.png" mimeType:@"image/png"];
                }
            } error:nil];
            
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            NSProgress *progress = nil;
            
            NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
                [FMToast hide];
                [self loadFirstPage]; // 重新加载列表
                if(!error) {
                    [FMToast showMessage:LocalStringCommon(@"OPER_SUCC")];
                } else {
                    [FMToast showMessage:LocalStringCommon(@"OPER_FAIL")];
                }
            }];
            
            [uploadTask resume];
        });
    }];
}

@end
